package org.dromara.common.security.handler

import cn.hutool.core.util.ReUtil
import org.dromara.common.core.utils.SpringUtils
import org.springframework.beans.factory.InitializingBean
import org.springframework.web.servlet.mvc.method.RequestMappingInfo
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
import org.springframework.web.util.pattern.PathPattern
import java.util.*
import java.util.function.Consumer
import java.util.regex.Pattern

/**
 * 获取所有Url配置
 *
 * @author LikeYouDo
 * @date 2025/7/17
 */

class AllUrlHandler : InitializingBean {
    companion object {
        private val PATTERN: Pattern = Pattern.compile("\\{(.*?)\\}")
    }

    var urls: MutableList<String> = ArrayList()

    override fun afterPropertiesSet() {
        val set: MutableSet<String> = HashSet<String>()
        val mapping: RequestMappingHandlerMapping = SpringUtils.getBean(
            "requestMappingHandlerMapping", RequestMappingHandlerMapping::class.java
        )
        val map = mapping.handlerMethods
        map.keys.forEach({ info: RequestMappingInfo ->
            // 获取注解上边的 path 替代 path variable 为 *
            info.pathPatternsCondition?.let {
                it.patterns.forEach(Consumer { url: PathPattern ->
                    set.add(
                        ReUtil.replaceAll(
                            url.patternString, PATTERN, "*"
                        )
                    )
                })
            }
        })
        urls.addAll(set)
    }
}
